import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import UnoCSS from "unocss/vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import { resolve } from "path";
import ViteRestart from "vite-plugin-restart";
import viteCompression from "vite-plugin-compression";

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());

  return {
    plugins: [
      viteCompression(),
      vue(),
      UnoCSS({
        hmrTopLevelAwait: false,
      }),
      AutoImport({
        imports: ["vue", "@vueuse/core", "pinia", "vue-router"],
        eslintrc: {
          enabled: true,
          filepath: "./.eslintrc-auto-import.json",
          globalsPropValue: true,
        },

        resolvers: [ElementPlusResolver(), IconsResolver({})],
        vueTemplate: true, // 是否在 vue 模板中自动导入
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({
            enabledCollections: ["ep"], // element-plus图标库，其他图标库 https://icon-sets.iconify.design/
          }),
        ],
        // 指定自定义组件位置(默认:src/components)
        dirs: ["src/components", "src/**/components"],
      }),
      createSvgIconsPlugin({
        // 指定缓存文件夹
        iconDirs: [resolve(process.cwd(), "src/assets/svg")],
        // 指定symbolId格式
        symbolId: "icon-[dir]-[name]",
      }),
      Icons({
        // 自动安装图标库
        autoInstall: true,
      }),
      ViteRestart({
        restart: ["my.config.[jt]s"],
      }),
    ],
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"),
      },
    },
    css: {
      // CSS 预处理器
      preprocessorOptions: {
        // 定义全局 SCSS 变量
        scss: {
          javascriptEnabled: true,
          additionalData: `
            @use "@/styles/variables.scss" as *;
          `,
        },
      },
    },
    server: {
      // 允许IP访问
      host: "0.0.0.0",
      // 应用端口 (默认:3000)
      port: Number(env.VITE_APP_PORT),
      // 运行是否自动打开浏览器
      open: true,
      proxy: {
        /**
         * env.VITE_APP_BASE_API: /dev-api
         */
        [env.VITE_APP_BASE_API]: {
          changeOrigin: true,
          // 线上接口地址
          target: env.VITE_APP_API_URL,

          rewrite: (path) =>
            path.replace(new RegExp("^" + env.VITE_APP_BASE_API), ""),
        },
      },
    },
    build: {
      outDir: "dist", // 指定输出路径
      assetsDir: "assets", // 指定生成静态文件目录
      emptyOutDir: true, // 构建时清空该目录
      terserOptions: {
        compress: {
          // 打包的时候可以移除console和debugger
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          chunkFileNames: "js/[name]-[hash].js",
          entryFileNames: "js/[name]-[hash].js",
          assetFileNames: "[ext]/[name]-[hash].[ext]",
        },
      },
      // 对打包出来的资源文件进行分类，分别放到不同的文件夹内
      assetFileNames(assetsInfo) {
        //  css样式文件
        if (assetsInfo.name?.endsWith(".css")) {
          return "css/[name]-[hash].css";
        }
        //  字体文件
        const fontExts = [".ttf", ".otf", ".woff", ".woff2", ".eot"];
        if (fontExts.some((ext) => assetsInfo.name?.endsWith(ext))) {
          return "font/[name]-[hash].[ext]";
        }

        //  图片文件
        const imgExts = [".png", ".jpg", ".jpeg", ".webp", ".gif", ".icon"];
        if (imgExts.some((ext) => assetsInfo.name?.endsWith(ext))) {
          return "img/[name]-[hash].[ext]";
        }

        //  SVG类型的图片文件
        const imgSvg = [".svg"];
        if (imgSvg.some((ext) => assetsInfo.name?.endsWith(ext))) {
          return "assest/icons/[name].[ext]";
        }

        //  视频文件
        const videoExts = [".mp4", ".avi", ".wmv", ".ram", ".mpg", "mpeg"];
        if (videoExts.some((ext) => assetsInfo.name?.endsWith(ext))) {
          return "video/[name]-[hash].[ext]";
        }
        //  其它文件: 保存在 assets/图片名-哈希值.扩展名
        return "assets/[name]-[hash].[ext]";
      },
    },
  };
});
